<?php

namespace app\common\model;

use org\util\FileUtil;
use think\Cache;
use think\Db;
use think\helper\Str;

class MoudleModel extends BaseModel
{

    protected $name = 'moudle'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /*读取器*/
    protected function getIsSystemTextAttr($value, $data)
    {
        $status = [0 => '普通模型', 1 => '系统模型'];
        return $status[$data['is_system']];
    }

    protected function getEnableTextAttr($value, $data)
    {
        $status = [0 => '关闭', 1 => '开启'];
        return $status[$data['enable']];
    }

    protected function getIsBindTextAttr($value, $data)
    {
        $status = [0 => '独立模型', 1 => 'cms模型'];
        return $status[$data['is_bind']];
    }
    /**
     * 获取可绑定模型
     */
    public function getBindMoudle(){
        $moudle = Cache::get('moudle');
        foreach($moudle as $k=>$v){
            if($v['is_bind']==0){
                unset($moudle[$k]);
            }
        }
        return $moudle;
    }
    /**
     * 更新模型缓存
     */
    public function updateCache(){
        $moudle = $this->order('moudle_sort')->column('*','mid');
        return Cache::set('moudle',$moudle);
    }
    /**
     * 更新表配置缓存
     */
    public function updateTableCache($mid)
    {
        try {
            $moudleInfo = $this->where('mid', $mid)->find();
            if(!empty($moudleInfo)){
                $fieldMoudle = new FieldModel();
                $fieldList = $fieldMoudle->where('mid', $mid)->order('field_sort')->select();
                $fieldList = obj2array($fieldList);
                $cacheData = [];
                foreach ($fieldList as $field) {
                    $cacheData[$field['field_name']] = $field;
                }
                cache($moudleInfo['table_name'], $cacheData);
                return true;
            }else{
                exception('对应模型不存在！');
            }
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            exception($e->getMessage());
        }
    }

    /**
     * 添加模型
     * @param $data
     */
    public function addData($data)
    {
        self::startTrans();
        try {
            if ($this->getByTableName($data['table_name'])) {
                exception('模型表名已存在!',40001);
            } else {
                $this->isUpdate(false)->allowField(true)->save($data); //添加模型记录
                $tableName = $data['table_name']; //获取表名
                if($data['is_bind']==1){
                    $sql = file_get_contents(APP_PATH . 'system/sql/cms_moudle.sql');
                }else{
                    $sql = file_get_contents(APP_PATH . 'system/sql/base_moudle.sql');
                }
                $sql = preg_replace(['/@pre@/', '/@table@/', '/@table_comment@/'], [config('database.prefix'), $tableName, $data['description']], $sql);
                $this->execute($sql);
                $this->FieldInit($this->getAttr('mid'), $tableName,$data['is_bind']);
                self::commit();
            }
        } catch (\Exception $e) {
            self::rollback();
            exception($e->getMessage(),40001);
        }
        return true;
    }

    /**
     * 删除模型
     */
    public function delData($mid)
    {
        //开启事务
        Db::startTrans();
        try {
            //验证栏目信息
            if (Db::table('category')->where('mid', $mid)->find()) {
                exception('请先删除模型栏目!',40001);
            }
            $tableName = Db::table('moudle')->where('mid', $mid)->value('table_name');
            Cache::rm($tableName); //删除表配置缓存文件
            //删除表记录
            Db::table('moudle')->where('mid', $mid)->delete();
            //删除字段记录
            Db::table('field')->where('mid', $mid)->delete();
            //删除对应表
            Db::execute('DROP TABLE IF EXISTS `' . config('database.prefix') . $tableName . '`');
            Db::commit(); // 提交事务
        } catch (\Exception $e) {
            Db::rollback(); // 回滚事务
            exception($e->getMessage(),40001);
        }
        //删除对应文件
        FileUtil::unlinkFile(APP_PATH . '/common/model/app/' . Str::studly($tableName) . 'Model.php');
        return true;
    }


    //字段初始化
    private function FieldInit($mid, $tableName,$is_bind=1)
    {
        $dataList = [
            [
                'mid' => $mid,
                'table_name' => $tableName,
                'table_type' => 1,
                'enable' => 1,
                'is_system' => 1,
                'title' => '标题',
                'field_name' => 'title',
                'field_type' => 'input',
                'field_sort' => 1,
                'set' => '{"layout":"1","size":"10","length":"100","default":""}',
                'validate' => '["require"]',
                'tips' => '',
                'validate_scene' => 3,
            ],
            [
                'mid' => $mid,
                'table_name' => $tableName,
                'table_type' => 1,
                'enable' => 1,
                'is_system' => 1,
                'title' => '排序',
                'field_name' => 'sort',
                'field_type' => 'number',
                'field_sort' => 101,
                'set' => '{"layout":"2","size":"4","num_integer":"11","num_decimal":"0","field_type":"int","default":"0"}',
                'validate' => '["require"]',
                'tips' => '',
                'validate_scene' => 3,
            ]
        ];
        if($is_bind==1){
            $cmsDataList=[[
                'mid' => $mid,
                'table_name' => $tableName,
                'table_type' => 1,
                'enable' => 1,
                'is_system' => 1,
                'title' => '点击量',
                'field_name' => 'click',
                'field_type' => 'number',
                'field_sort' => 102,
                'set' => '{"layout":"2","size":"4","num_integer":"4","num_decimal":"0","field_type":"int","default":"0"}',
                'validate' => '["number"]',
                'tips' => '',
                'validate_scene' => 3,
            ],[
                'mid' => $mid,
                'table_name' => $tableName,
                'table_type' => 1,
                'enable' => 1,
                'is_system' => 1,
                'title' => '绑定模板',
                'field_name' => 'content_tpl',
                'field_type' => 'tpl',
                'field_sort' => 103,
                'set' => '{"layout":"2","size":"4","length":"50","default":""}',
                'validate' => '["require"]',
                'tips' => '',
                'validate_scene' => 3,
            ],[
                'mid' => $mid,
                'table_name' => $tableName,
                'table_type' => 1,
                'enable' => 1,
                'is_system' => 1,
                'title' => '栏目分类',
                'field_name' => 'cid',
                'field_type' => 'cid',
                'field_sort' => 2,
                'set' => '{"layout":"1","size":"4"}',
                'validate' => '["require","number"]',
                'tips' => '',
                'validate_scene' => 3,
            ]];
            $dataList = array_merge($dataList,$cmsDataList);
        }
        return Db::table('field')->insertAll($dataList);
    }

}